import { BadRequestException, Inject, Injectable } from '@nestjs/common';
import { RegisterUserDto } from './dto/register-user.dto';
import { DbService } from 'src/db/db.service';
import { User } from './entities/user.entity';
import { LoginUserDto } from './dto/login-user.dto';
import { JwtService } from '@nestjs/jwt';
import { Response } from 'express';
import * as crypto from 'crypto';
@Injectable()
export class UserService {
  @Inject(DbService)
  dbService: DbService;

  @Inject(JwtService)
  jwtService: JwtService;

  static foundUser: User;

  /**
   * 生成SHA-256哈希
   * @param password 原始密码
   * @returns SHA-256哈希字符串
   */
  private generateSHA256Hash(password: string): string {
    return crypto.createHash('sha256').update(password).digest('hex');
  }

  async register(registerUserDto: RegisterUserDto) {
    const users: User[] = await this.dbService.read();
    const foundUser = users.find(item => item.username === registerUserDto.username);
    if (foundUser) {
      throw new BadRequestException('该用户已经注册');
    }
    const user = new User();
    user.username = registerUserDto.username;
    // 如果前端传来的密码已经是SHA-256哈希，直接存储；否则进行哈希处理
    user.password = registerUserDto.password.length === 64 ? registerUserDto.password : this.generateSHA256Hash(registerUserDto.password);
    users.push(user);
    await this.dbService.write(users);
    return user;
  }

  async login(loginUserDto: LoginUserDto,res: Response) {
    const users: User[] = await this.dbService.read();
    const foundUser = users.find(item => item.username === loginUserDto.username);
    if (!foundUser) {
      throw new BadRequestException('用户不存在');
    }
    if (foundUser.password !== loginUserDto.password) {
      throw new BadRequestException('密码不正确');
    }
    const token = await this.jwtService.signAsync({
      id: foundUser.username,
      username: foundUser.username,
    });
    UserService.foundUser = foundUser;
    // res.setHeader('token', token);
    return {
      code: 200,
      message: '登录成功',
      data: {
        ...foundUser,
        token
      }
    }
  }

  async getUserInfo(){
    console.log(UserService.foundUser,"UserService.foundUser");
    const userInfo = UserService.foundUser
    return {
      code: 200,
      message: '获取用户信息成功',
      data: userInfo
    }
  }

  async logout(res: Response) {
    res.clearCookie('token');
    return {
      code: 200,
      message: '退出登录成功'
    }
  }

  async getUserList() {
    const users: User[] = await this.dbService.read();
    return {
      code: 200,
      message: '获取用户列表成功',
      data: users
    }
  }

  async addUser(data: any) {
    const users: User[] = await this.dbService.read();
    const foundUser = users.find(item => item.username === data.username);
    if (foundUser) {
      throw new BadRequestException('该用户已经存在');
    }
    const user = new User();
    user.username = data.username;
    user.password = data.password
    user.userrole = data.userrole;
    users.push(user);
    await this.dbService.write(users);
    return {
      code: 200,
      message: '添加用户成功',
      data: user
    };
  }

  async deleteUser(data: any) {
    const users: User[] = await this.dbService.read();
    const userIndex = users.findIndex(item => item.username === data.username);
    if (userIndex === -1) {
      throw new BadRequestException('用户不存在');
    }
    const deletedUser = users.splice(userIndex, 1)[0];
    await this.dbService.write(users);
    return {
      code: 200,
      message: '删除用户成功',
      data: deletedUser
    };
  }

  async editUser(data: any) {
    const users: User[] = await this.dbService.read();
    const userIndex = users.findIndex(item => item.username === data.username);
    if (userIndex === -1) {
      throw new BadRequestException('用户不存在');
    }
    const user = users[userIndex];
    if (data.password) {
      user.password = data.password
    }
    await this.dbService.write(users);
    return {
      code: 200,
      message: '编辑用户成功',
      data: user
    };
  }

}
